from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from framework.base_page import BasePage
from page.search_model import SearchModel
from page.search_result import SearchResult


class AdvancedSearchPage(BasePage):
    def __init__(self, driver:None):
        super().__init__(driver)

    def advanced_search(self, model:SearchModel):
        #第一步在搜索中输入keyword
        self.find(By.CSS_SELECTOR,".search-bar>input").send_keys(model.keyword)
        #第二步输入分类
        self.click(By.ID, 'search-in-category-header')
        self.sendkeys(By.CSS_SELECTOR,"[name='filter-input-search']", model.category)
        self.click(By.CSS_SELECTOR, f"[title={model.category}]")
        #第三步选话题
        self.click(By.ID, "search-status-options")
        self.click(By.CSS_SELECTOR, "#search-status-options li[title='"+ model.topic + "']")
        #第四步选择标签
        self.click(By.ID, "search-with-tags")
        self.sendkeys(By.CSS_SELECTOR, '#search-with-tags input[name=filter-input-search]', model.tag)
        self.click(By.CSS_SELECTOR,"li[title='" + model.tag + "']")
        self.find(By.CSS_SELECTOR, '#search-with-tags input[name=filter-input-search]').clear()
        self.click(By.ID, "search-with-tags")
        #第五步点击搜索
        self.click(By.CSS_SELECTOR, "button[aria-label='搜索']")
        self.driver.implicitly_wait(10)
        return self.get_result()

    def get_result(self):
        result_list = []
        result_elements = self.finds(By.CSS_SELECTOR, ".search-results .fps-result-entries div[role='listitem']")
        for result_element in result_elements:
            search_result = SearchResult()
            #获取标题
            search_result.title = result_element.find_element(By.CSS_SELECTOR, ".topic-title .ember-view").text
            # 获取内容
            search_result.content = \
                result_element.find_element(By.CSS_SELECTOR, ".fps-topic>.blurb.container>.ember-view").text
            # 获取分类
            search_result.category = result_element.find_element(By.CSS_SELECTOR, ".fps-topic .search-category .category-name").text
            # 获取标签
            search_result.tag = result_element.find_element(By.CSS_SELECTOR, ".fps-topic .discourse-tags a").text

            result_list.append(search_result)
        return result_list














